<template>
  <div class="max-box set-padding">
    <!-- 头部搜索、操作 -->
    <div class="header-box">
      <div class="header-left">
        <span>维保记录</span>
      </div>
      <!-- <a-input-search
          placeholder="输入维保记录名称"
          @search="getTableList"
          allow-clear
          v-model="title"
          class="search-box"
        >
          <a-button slot="enterButton" icon="search"></a-button>
        </a-input-search> -->
      <a-button type="primary" class="add-btn" @click="openTopDrawer"
        >添加新维保记录</a-button
      >
    </div>
    <!-- 内容区 -->
    <div class="content-box">
      <!-- 表格内容 -->
      <div class="table-box" ref="yHeight">
        <!-- 表格 -->
        <myTable
          :columns="columns"
          :dataSource="tableData"
          :total="total"
          @changePagination="getTableList"
          :scroll="{ x: 200, y: yHeight }"
        >
          <template #titleslot="slotData">
            <div @click="toDetail(slotData.scope)" class="title-box">
              {{ slotData.scope.title }}
            </div>
          </template>
          <template #systemType="slotData">
            {{ slotData.scope.maintenanceType == 1 ? "电站" : "--" }}
          </template>
          <template #maintenanceObject="slotData">
            {{ slotData.scope.maintenanceObject == 1 ? "设备" : "其他" }}
          </template>
          <template slot="operation" slot-scope="slotData">
            <div class="operation-box">
              <a-icon
                type="edit"
                title="编辑"
                @click="editOpen(slotData.scope.id)"
              />
              <a-icon
                type="delete"
                class="icon-left"
                title="删除"
                @click="deleteOne(slotData.scope)"
              />
            </div>
          </template>
        </myTable>
      </div>
    </div>
    <!-- 添加维保记录-->
    <a-drawer
      placement="top"
      :closable="false"
      :visible="addVisible"
      height="100%"
      wrapClassName="add-power"
      @close="closeTopDrawer"
      :destroyOnClose="true"
      :headerStyle="{
        background: '#f0f1f5',
        padding: '0 0.2rem 0 0.3rem',
        flexGrow: 0,
      }"
      :bodyStyle="{
        padding: '0.3rem 0 0 0',
        flexGrow: 1,
      }"
      :drawerStyle="{
        display: 'flex',
        flexDirection: 'column',
      }"
    >
      <template #title>
        <div class="head-box">
          <span>添加维保记录</span>
          <div class="head-btn">
            <a-button @click="closeTopDrawer">取消</a-button>
            <a-button type="primary" class="save-btn" @click="savePlan"
              >保存</a-button
            >
          </div>
        </div>
      </template>
      <div class="content-box">
        <a-form-model ref="ruleForm" :model="form" :rules="rules">
          <div class="width70">
            <a-form-model-item label="名称" prop="title" required>
              <a-input v-model="form.title" class="input-width"></a-input>
            </a-form-model-item>
            <a-form-model-item label="维保人" prop="userEntities" required>
              <div class="model-box">
                <template v-if="chooseUserList.length > 0">
                  <div class="member-box" v-for="i in chooseUserList">
                    <div class="station-text">{{ i.name + i.id }}</div>
                    <a-icon
                      type="close"
                      class="close-icon"
                      @click="deleteMember(i.id)"
                    />
                  </div>
                </template>

                <div class="add-btn" @click="openModal('MemberModal')">
                  <a-icon type="plus" />
                  成员
                </div>
              </div>
            </a-form-model-item>
            <div class="system-box">
              <div class="system-50 pr-32">
                <a-form-model-item
                  label="维保系统"
                  prop="stationId"
                  required
                  class="input-item"
                >
                  <div class="system-main">
                    <myDrop
                      :dropdownList="priorityList"
                      :defaultFlag.sync="form.maintenanceType"
                      class="priority-box"
                    ></myDrop>

                    <div class="model-box flex1">
                      <div class="member-box" v-if="form.stationId">
                        <div class="station-text">
                          {{ stationName + form.stationId }}
                        </div>
                        <a-icon
                          type="close"
                          class="close-icon"
                          @click="deleteStation"
                        />
                      </div>
                      <div
                        class="add-btn"
                        @click="openModal('StationModal')"
                        v-else
                      >
                        <a-icon type="plus" />
                        电站
                      </div>
                    </div>
                  </div>
                </a-form-model-item>
              </div>
              <div
                class="system-50 pl-32"
                v-if="form.stationId && form.maintenanceObject == 1"
              >
                <a-form-model-item
                  label="维保对象"
                  prop="deviceEntities"
                  required
                >
                  <div class="system-main">
                    <myDrop
                      :dropdownList="maintenanceObjList"
                      :defaultFlag.sync="form.maintenanceObject"
                      class="priority-box"
                    ></myDrop>

                    <div class="model-box flex1">
                      <template v-if="chooseDeviceList.length != 0">
                        <div
                          class="member-box"
                          v-for="device in chooseDeviceList"
                        >
                          <div class="station-text">
                            {{ device.deviceTitle + device.deviceSn }}
                          </div>
                          <a-icon
                            type="close"
                            class="close-icon"
                            @click="deleteDevice(device.deviceSn)"
                          />
                        </div>
                      </template>

                      <div class="add-btn" @click="openModal('DeviceModal')">
                        <a-icon type="plus" />
                        设备
                      </div>
                    </div>
                    <!-- <a-input
                      v-model="form.maintenanceOther"
                      v-else
                      class="input-style"
                    ></a-input> -->
                  </div>
                </a-form-model-item>
              </div>
              <div
                class="system-50 pl-32"
                v-if="form.stationId && form.maintenanceObject == 2"
              >
                <a-form-model-item
                  label="维保对象"
                  prop="maintenanceOther"
                  required
                >
                  <div class="system-main">
                    <myDrop
                      :dropdownList="maintenanceObjList"
                      :defaultFlag.sync="form.maintenanceObject"
                      class="priority-box"
                    ></myDrop>
                    <a-input
                      v-model="form.maintenanceOther"
                      class="input-style"
                    ></a-input>
                  </div>
                </a-form-model-item>
              </div>
            </div>
            <a-form-model-item label="维保时间" prop="maintenanceTime" required>
              <a-date-picker
                v-model="form.maintenanceTime"
                :allowClear="false"
                showTime
                :showToday="false"
              />
            </a-form-model-item>
            <a-form-model-item label="维保内容" prop="maintenanceDesc" required>
              <a-textarea
                :auto-size="{ minRows: 2, maxRows: 6 }"
                v-model="form.maintenanceDesc"
              />
            </a-form-model-item>
            <a-form-model-item label="备注" prop="remark">
              <a-textarea
                :auto-size="{ minRows: 2, maxRows: 6 }"
                v-model="form.remark"
              />
            </a-form-model-item>
          </div>
        </a-form-model>
      </div>
    </a-drawer>
    <!-- 成员选择 -->
    <MemberModal
      ref="MemberModal"
      @onSubmit="changeMember"
      :userList.sync="form.userEntities"
    ></MemberModal>
    <!-- 电站选择 -->
    <StationModal
      ref="StationModal"
      :id.sync="form.stationId"
      :name.sync="stationName"
      @onSubmit="stationChoose"
    ></StationModal>

    <DeviceModal
      ref="DeviceModal"
      :stationId="form.stationId"
      :deviceList.sync="form.deviceEntities"
      @onSubmit="getDevice"
    ></DeviceModal>
    <maintenanceDetailPage
      :id="maintenanceId"
      :detailVisible.sync="detailVisible"
      @deleteMaintenance="deleteMaintenance"
      @editMaintenance="editMaintenance"
    />
  </div>
</template>
<script>
import moment from "moment";
import {
  maintenanceList,
  addMaintenance,
  maintenanceDetail,
  maintenanceUpdate,
  maintenanceDelete,
} from "@/api/maintenance.js";
import maintenanceDetailPage from "@/views/operationMaintenance/components/maintenanceDetailPage";
import { debound } from "@/utils/index.js";
// import echartConfig from "./config/alarmEchart";
export default {
  data() {
    return {
      title: "",
      yHeight:
        document.documentElement.clientHeight -
        document.documentElement.clientHeight / 4.9,
      columns: [
        {
          title: "序号",
          dataIndex: "index",
          width: 70,
          customRender: (text, record, index) => {
            return index + 1;
          },
          fixed: "left",
          align: "center",
        },
        {
          title: "名称",
          dataIndex: "title",
          scopedSlots: {
            customRender: "titleslot",
          },
          width: 120,
        },

        {
          title: "维保时间",
          dataIndex: "maintenanceTime",
          width: 90,
        },
        {
          title: "维保系统类型",
          scopedSlots: {
            customRender: "systemType",
          },
          width: 120,
        },
        {
          title: "维保系统",
          dataIndex: "stationId",
        },
        {
          title: "维保对象类型",
          width: 120,
          scopedSlots: {
            customRender: "maintenanceObject",
          },
        },

        {
          title: "管理者",
          width: 120,
        },

        {
          title: "创建时间",
          width: 120,
          dataIndex: "createTime",
        },
        {
          title: "更新时间",
          width: 120,
        },
        {
          title: "操作",
          scopedSlots: {
            customRender: "operation",
          },
        },
      ],
      tableData: [
        {
          deviceSn: "88888",
        },
      ],
      total: 0,
      moment,
      addVisible: false,
      form: {
        title: "",
        stationId: "",

        adminUser: "",
        userEntities: [],
        maintenanceType: "1",
        maintenanceObject: "1",
        maintenanceTime: moment(),
        maintenanceDesc: "", //描述
        maintenanceOther: "", //其他的内容
        deviceEntities: [], //设备
        remark: "", //备注
      },
      chooseDeviceList: [],
      chooseUserList: [],
      stationName: "",
      memberName: "",
      rules: {
        title: [
          {
            required: true,
            message: "请填写名称",
            trigger: "blur",
          },
        ],
        stationId: [
          {
            required: true,
            message: "请选择电站",
            trigger: ["blur", "change"],
          },
        ],
        userEntities: [
          {
            required: true,
            message: "请选择维保人员",
            trigger: ["blur", "change"],
          },
        ],
        deviceEntities: [
          {
            required: true,
            message: "请选择维保设备",
            trigger: ["blur", "change"],
          },
        ],
        maintenanceOther: [
          {
            required: true,
            message: "请填写其他内容",
            trigger: "blur",
          },
        ],
        maintenanceDesc: [
          {
            required: true,
            message: "请填写维保描述",
            trigger: "blur",
          },
        ],
      },
      priorityList: [
        {
          value: "1",
          label: "电站",
        },
      ],
      maintenanceObjList: [
        {
          value: "1",
          label: "设备",
        },
        {
          value: "2",
          label: "其他",
        },
      ],
      maintenanceId: "",
      detailVisible: false,
    };
  },
  components: { maintenanceDetailPage },
  methods: {
    onSearch() {},
    watchResize() {
      this.yHeight = this.$refs["yHeight"].clientHeight - 100;
      window.addEventListener("resize", this.screenResize);
    },
    screenResize: debound(function () {
      // document.documentElement.clientHeight;

      this.yHeight = this.$refs["yHeight"].clientHeight - 100;
    }, 200),
    openTopDrawer() {
      this.addVisible = true;
    },
    closeTopDrawer() {
      this.$refs.ruleForm.resetFields();
      this.form.id = "";
      this.addVisible = false;
    },
    changeTab(value) {
      this.activeTab = value;

      this.getTableList();
    },
    onClose() {
      this.visible = false;
    },
    stationChoose() {
      this.form.deviceEntities = [];
      this.chooseDeviceList = [];
    },
    // 获取表格数据
    getTableList(pageMsg) {
      let requestPage = {
        page: 1,
        limit: 50,
        title: this.title,
        stationId: this.$route.query.id,
      };
      requestPage.stationId || delete requestPage.stationId;
      requestPage.title || delete requestPage.title;
      if (pageMsg?.page) {
        requestPage.page = pageMsg.page;
        requestPage.limit = pageMsg.pageSize;
      }
      maintenanceList({ ...requestPage }).then((res) => {
        this.tableData = res.data;
        this.total = res.count;
      });
    },
    savePlan() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const reuqestData = JSON.parse(JSON.stringify(this.form));
          reuqestData.deviceEntities = this.chooseDeviceList.map((item) => {
            return {
              deviceSn: item.deviceSn,
              deviceTitle: item.deviceTitle,
            };
          });
          reuqestData.userEntities = this.chooseUserList;
          reuqestData.maintenanceTime = moment(
            reuqestData.maintenanceTime
          ).format("YYYY-MM-DD HH:mm:ss");
          if (reuqestData.maintenanceObject == 1) {
            delete reuqestData.maintenanceOther;
          } else {
            delete reuqestData.deviceEntities;
          }
          let requestApi = this.form.id ? maintenanceUpdate : addMaintenance;
          requestApi(reuqestData)
            .then((res) => {
              this.$message.success(
                `${this.form.id ? "修改" : "添加"}维保记录成功`
              );
              this.addVisible = false;
              this.$refs.ruleForm.resetFields();
              this.form.id = "";
              console.log(this.form, "------this.form.id ?---");
              this.getTableList();
            })
            .catch((err) => {
              // this.addVisible = false;
            });
        } else {
          return false;
        }
        console.log(valid);
      });
    },
    // 选择成员回调
    changeMember(user) {
      // let { id, name, headImgUrl } = e;
      // this.form.adminUser = id;
      // this.memberName = name;
      this.chooseUserList = user;
    },
    deleteMember(id) {
      this.form.userEntities = this.form.userEntities.filter((item) => {
        return item != id;
      });
      this.chooseUserList = this.chooseUserList.filter((item) => {
        return item.id != id;
      });
    },
    openModal(refs) {
      this.$refs[refs].openModal();
    },
    deleteStation() {
      this.form.stationId = "";
      this.stationName = "";
    },
    getDevice(device) {
      this.chooseDeviceList = device;
    },
    deleteDevice(sn) {
      this.form.deviceEntities = this.form.deviceEntities.filter((item) => {
        return item != sn;
      });
      this.chooseDeviceList = this.chooseDeviceList.filter((item) => {
        return item.deviceSn != sn;
      });
    },
    editOpen(id) {
      maintenanceDetail({ id }).then((res) => {
        console.log(res);
        this.form = JSON.parse(JSON.stringify(res.data));
        this.chooseDeviceList = res.data.deviceEntities;
        this.chooseUserList = res.data.userEntities;
        this.form.userEntities = this.form.userEntities.map((item) => {
          return item.id;
        });
        delete this.form.token;
        this.form.deviceEntities = this.form.deviceEntities.map((item) => {
          return item.deviceSn;
        });
        this.form.maintenanceTime = moment(this.form.maintenanceTime);
        this.addVisible = true;
      });
    },
    deleteOne(row) {
      this.$confirm({
        title: `确认删除${row.title}?`,
        okText: "确认",
        cancelText: "取消",
        onOk: () => {
          console.log("OK");
          this.detailVisible = false;
          maintenanceDelete({ id: row.id }).then((res) => {
            this.$message.success("删除成功");
            this.getTableList();
          });
        },
        onCancel: () => {
          console.log("Cancel");
        },
      });
    },
    toDetail(row) {
      this.maintenanceId = row.id;
      this.detailVisible = true;
    },
    deleteMaintenance(row) {
      this.deleteOne(row);
    },
    editMaintenance(row) {
      this.editOpen(row.id);
    },
  },
  mounted() {
    if (this.$route.path == "/station/maintenanceRecord") {
      this.$nextTick(() => {
        document.getElementsByClassName("set-padding")[0].style.paddingLeft =
          "16px";
        document.getElementsByClassName("set-padding")[0].style.paddingRight =
          "16px";
        document.getElementsByClassName("set-padding")[0].style.paddingBottom =
          "10px";
      });
    }
    this.getTableList();
    this.watchResize();
  },
  computed: {},
  beforeDestroy() {
    window.removeEventListener("resize", this.screenResize);
  },
};
</script>
<style lang="less" scoped>
.max-box {
  width: 100%;
  padding-top: 16px;
  padding-right: 20px;
  box-sizing: border-box;
  height: 100%;
  display: flex;
  flex-direction: column;
  .header-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    // padding-right: 20px;
    margin-bottom: 16px;
    .header-left {
      span {
        font-size: 18px;
        color: #252b3a;
      }
      i {
        font-size: 20px;
      }
    }
    .search-box {
      width: 240px;
      height: 32px;
      /deep/.ant-input {
        font-size: 12px;
      }
    }
    .add-btn {
      font-size: 12px;
    }
  }
  .content-box {
    background: #fff;
    width: 100%;
    flex-grow: 1;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    // tabs
    .content-head {
      display: flex;
      padding: 16px;

      align-items: center;
      span {
        font-size: 14px;
        margin-right: 16px;
      }
    }
    .table-box {
      min-height: 220px;
      flex-grow: 1;
      .name-box {
        cursor: pointer;
      }
    }
    .title-box {
      cursor: pointer;
    }
    // 操作样式
    .operation-box {
      width: 100%;
      padding-left: 15px;
      font-size: 16px;
      i {
        cursor: pointer;
        transition: all 0.5s;
        &:hover {
          color: #048fff;
        }
      }
      .icon-left {
        margin-left: 30px;
      }
    }
  }
}
/deep/.screen-drawer {
  .ant-drawer-content-wrapper {
    height: 200px !important;
  }
}
.add-power {
  .head-box {
    display: flex;
    height: 64px;
    align-items: center;
    justify-content: space-between;
    span {
      font-size: 20px;
      color: #252b3a;
    }
    .head-btn {
      .ant-btn {
        height: 32px;
        font-size: 12px;
        margin-left: 10px;
      }
    }
  }
  .content-box {
    width: 100%;
    .input-width {
      height: 32px;
    }
    .width70 {
      width: 70%;
      margin: 0 auto;
      .ant-row {
        margin-bottom: 10px;
      }
      .model-box {
        width: 100%;
        height: 32px;
        padding: 2px 32px 2px 12px;
        border: 1px solid #d9d9d9;
        border-radius: 2px;
        display: flex;
        align-items: center;
        .member-box {
          height: 22px;
          padding: 0 8px;
          border-radius: 2px;
          background-color: rgba(0, 0, 0, 0.04);
          display: flex;
          align-items: center;
          margin-right: 16px;
          .station-text {
            max-width: 480px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-size: 12px;
          }
          .close-icon {
            font-size: 12px;
            margin-left: 12px;
            cursor: pointer;
            &:hover {
              color: #ff7875;
            }
          }
        }
        .add-btn {
          font-size: 12px;
          color: #048fff;
          display: flex;
          align-items: center;
          cursor: pointer;
          height: max-content;
        }
      }
      .system-box {
        display: flex;
        .system-50 {
          width: 50%;
          // .input-item {
          //   width: 100%;

          .system-main {
            width: 100%;
            display: flex;
            .input-style {
              height: 32px;
            }
            .priority-box {
              width: 30%;
              height: 32px;
              margin-right: 4px;
              display: flex;
              align-items: center;
              justify-content: space-between;
            }
            .flex1 {
              flex-grow: 1;
            }
          }
          // }
        }
        .pr-32 {
          padding-right: 32px;
        }
        .pl-32 {
          padding-left: 32px;
        }
      }
    }
  }
}
</style>
        